package com.shizhefei.indicator.moretab;

import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.shizhefei.indicator.demo.R;
import com.shizhefei.view.indicator.Indicator;
import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.IndicatorViewPager.IndicatorFragmentPagerAdapter;
import com.shizhefei.view.indicator.ScrollIndicatorView;
import com.shizhefei.view.indicator.slidebar.ColorBar;
import com.shizhefei.view.indicator.transition.OnTransitionTextListener;

import java.util.ArrayList;
import java.util.List;

/**
 *  tab + viewpager ，可实现 社区页面，左右滑动效果
 *  ps viewpager + viewpager嵌套 滑动事件
 */
public class MoreTabAndBannerActivity extends FragmentActivity {
    private IndicatorViewPager indicatorViewPager;
    private LayoutInflater inflate;
//    private String[] names = {"CUPCAKE", "DONUT", "FROYO", "GINGERBREAD", "HONEYCOMB", "ICE CREAM SANDWICH", "JELLY BEAN", "KITKAT"};
    private String[] names = {"热帖", "首页", "关注哈哈", "求助", "发现", "ICE CREAM SANDWICH", "JELLY BEAN", "KITKAT"};
    private ScrollIndicatorView scrollIndicatorView;
    private ToggleButton pinnedToggleButton;
    private ToggleButton splitAutotoggleButton;
    private List<View> tabIndicators;  //顶部indicators
    private List<Fragment> tabFrags; //fragment 页面集合
    private int unSelectTextColor;
    private ColorBar colorBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_moretab);
        splitAutotoggleButton = (ToggleButton) findViewById(R.id.toggleButton1);
        pinnedToggleButton = (ToggleButton) findViewById(R.id.toggleButton2);
        ViewPager viewPager = (ViewPager) findViewById(R.id.moretab_viewPager);
        scrollIndicatorView = (ScrollIndicatorView) findViewById(R.id.moretab_indicator);
        scrollIndicatorView.setBackgroundColor(Color.WHITE); //title背景色

        tabIndicators = new ArrayList<>();
        tabFrags = new ArrayList<>();

        colorBar = new  ColorBar(this, 0xFF2196F3, 4);
        colorBar.setWidth(dipToPix(40));
        scrollIndicatorView.setScrollBar(colorBar); //颜色值


        unSelectTextColor = Color.WHITE;
        // 设置滚动监听
        scrollIndicatorView.setOnTransitionListener(getTransitionTxtLis());

        viewPager.setOffscreenPageLimit(2);
        indicatorViewPager = new IndicatorViewPager(scrollIndicatorView, viewPager);
        inflate = LayoutInflater.from(getApplicationContext());
        indicatorViewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));

        //indicator点击item监听
        indicatorViewPager.setOnIndicatorItemClickListener(new Indicator.OnIndicatorItemClickListener() {
            @Override
            public boolean onItemClick(View clickItemView, int position) {
//                TextView textView = (TextView) clickItemView.findViewById(R.id.tv);
//                if(textView != null) {
//                    colorBar.setWidth(getTextWidth(textView));
//                }
//                clickItemView.findViewById(R.id.bubble).setVisibility(View.GONE);

                Log.i("thduan", "onItemClick: " + position);
                onPageSelected(position);
                return false;
            }
        });

        //page页面滑动监听
        indicatorViewPager.setOnIndicatorPageChangeListener(new IndicatorViewPager.OnIndicatorPageChangeListener() {
            @Override
            public void onIndicatorPageChange(int preItem, int currentItem) {
                Log.i("thduan", "onIndicatorPageChange: " + currentItem);
                onPageSelected(currentItem);

            }
        });

        // 默认true ，自动布局
        splitAutotoggleButton.setChecked(scrollIndicatorView.isSplitAuto());
        splitAutotoggleButton.setOnCheckedChangeListener(onCheckedChangeListener);
        pinnedToggleButton.setOnCheckedChangeListener(onCheckedChangeListener);

    }

    private void onPageSelected(int currentItem) {
        if(tabFrags.get(currentItem) instanceof MoreFragment) {
            ((MoreFragment) tabFrags.get(currentItem)).refresh();
        }
        View curIndicatorView = tabIndicators.get(currentItem);
        curIndicatorView.findViewById(R.id.bubble).setVisibility(View.GONE);

        TextView textView = (TextView) curIndicatorView.findViewById(R.id.tv);
        if(textView != null) {
            colorBar.setWidth(getTextWidth(textView));
        }
    }

    /**
     * 根据textview 内容长度计算，tabIndicator的宽度
     * @param textView
     * @return
     */
    private int getTextWidth(TextView textView) {
        if (textView == null) {
            return 0;
        }
        Rect bounds = new Rect();
        String text = textView.getText().toString();
        Paint paint = textView.getPaint();
        paint.getTextBounds(text, 0, text.length(), bounds);
        int width = bounds.left + bounds.width() + dipToPix(6); //加上6dp，比文字宽些好看
        return width;
    }

    private OnTransitionTextListener getTransitionTxtLis() {
        return new OnTransitionTextListener() {
            @Override
            public TextView getTextView(View tabItemView, int position) { //indicator整个中除了textview还包含其他view
                return (TextView) tabItemView.findViewById(R.id.tv);
            }
        }.setColor(Color.RED, Color.BLACK);
    }

    private OnCheckedChangeListener onCheckedChangeListener = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (buttonView == splitAutotoggleButton) {
                // 设置是否自动布局
                scrollIndicatorView.setSplitAuto(isChecked);
            } else if (buttonView == pinnedToggleButton) {
                scrollIndicatorView.setPinnedTabView(isChecked);
                // 设置固定tab的shadow，这里不设置的话会使用默认的shadow绘制
                scrollIndicatorView.setPinnedShadow(R.drawable.tabshadow, dipToPix(4));
                scrollIndicatorView.setPinnedTabBgColor(Color.RED);
            }
        }
    };

    private int size = 3;

    public void on3(View view) {
        size = 3;
        indicatorViewPager.getAdapter().notifyDataSetChanged();
    }

    public void on4(View view) {
        size = 4;
        indicatorViewPager.getAdapter().notifyDataSetChanged();
    }

    public void on5(View view) {
        size = 5;
        indicatorViewPager.getAdapter().notifyDataSetChanged();
    }

    public void on12(View view) {
        size = 12;
        indicatorViewPager.getAdapter().notifyDataSetChanged();
    }

    private class MyAdapter extends IndicatorFragmentPagerAdapter {

        public MyAdapter(FragmentManager fragmentManager) {
            super(fragmentManager);
        }

        @Override
        public int getCount() {
            return size;
        }

        @Override
        public View getViewForTab(int position, View convertView, ViewGroup container) {
            if (convertView == null) {
//                convertView = inflate.inflate(R.layout.tab_top, container, false);
                convertView = inflate.inflate(R.layout.tab_top_bubble, container, false);
                tabIndicators.add(convertView);
            }
            TextView textView = (TextView) convertView.findViewById(R.id.tv);
            textView.setText(names[position % names.length]);
            return convertView;
        }

        @Override
        public Fragment getFragmentForPage(int position) {
            if(position == 1) {
                MoreFragmentWithBanner fragment = new MoreFragmentWithBanner();
                Bundle bundle = new Bundle();
                bundle.putInt(MoreFragment.INTENT_INT_INDEX, position);
                fragment.setArguments(bundle);
                tabFrags.add(fragment);
                return fragment;
            }else {
                MoreFragment fragment = new MoreFragment();
                Bundle bundle = new Bundle();
                bundle.putInt(MoreFragment.INTENT_INT_INDEX, position);
                fragment.setArguments(bundle);
                tabFrags.add(fragment);
                return fragment;
            }


        }

        @Override
        public int getItemPosition(Object object) {
            //这是ViewPager适配器的特点,有两个值 POSITION_NONE，POSITION_UNCHANGED，默认就是POSITION_UNCHANGED,
            // 表示数据没变化不用更新.notifyDataChange的时候重新调用getViewForPage
            return PagerAdapter.POSITION_NONE;
        }

        private int getTextWidth(TextView textView) {
            if (textView == null) {
                return 0;
            }
            Rect bounds = new Rect();
            String text = textView.getText().toString();
            Paint paint = textView.getPaint();
            paint.getTextBounds(text, 0, text.length(), bounds);
            int width = bounds.left + bounds.width();
            return width;
        }

    }

    ;

    /**
     * 根据dip值转化成px值
     *
     * @param dip
     * @return
     */
    private int dipToPix(float dip) {
        int size = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, getResources().getDisplayMetrics());
        return size;
    }

}
